extends CharacterBody2D
class_name Tank

enum PLAYER_MODE{
	RED,
	GREEN
}

const SPEED = 300.0
const JUMP_VELOCITY = -400.0
const SMOKE = preload("res://scenes/smoke.tscn")
var bullet_count:int=5
var dying:bool=false
var round_time:float=0

@export var player:=PLAYER_MODE.RED
func _ready() -> void:
	if player==PLAYER_MODE.RED:
		$Icon.texture=load("res://assets/tank.png")
	else:
		$Icon.texture=load("res://assets/tank1.png")

func _physics_process(delta: float) -> void:
	if not dying:
		if player==PLAYER_MODE.RED:
			if Input.is_action_pressed("w"):
				velocity=Vector2(cos(rotation),sin(rotation))*50.0
			if Input.is_action_pressed("s"):
				velocity=Vector2(cos(rotation),sin(rotation))*-50.0
			if Input.is_action_pressed("a"):
				rotate(-PI/45)
			if Input.is_action_pressed("d"):
				rotate(PI/45)
			if Input.is_action_just_pressed("ui_accept"):
				if bullet_count>0:
					var blt=Bullet.generate_bullet(Vector2(cos(rotation),sin(rotation))*2.0,position+Vector2(cos(rotation),sin(rotation))*1.1)
					get_parent().add_child(blt)
					bullet_count-=1
				else:
					$BulletCountTimer.start()
			
		else:
			if Input.is_action_pressed("ui_up"):
				velocity=Vector2(cos(rotation),sin(rotation))*50.0
			if Input.is_action_pressed("ui_down"):
				velocity=Vector2(cos(rotation),sin(rotation))*-50.0
			if Input.is_action_pressed("ui_left"):
				rotate(-PI/45)
			if Input.is_action_pressed("ui_right"):
				rotate(PI/45)
			if Input.is_action_just_pressed("m"):
				if bullet_count>0:
					var blt=Bullet.generate_bullet(Vector2(cos(rotation),sin(rotation))*2.0,position+Vector2(cos(rotation),sin(rotation))*1.1)
					get_parent().add_child(blt)
					bullet_count-=1
				else:
					$BulletCountTimer.start()
			
	round_time+=delta
	if round_time>=0.8 and velocity.length()>0:
			var smoke:=SMOKE.instantiate()
			smoke.position=position
			get_parent().add_child(smoke)
	if round_time>=0.8:
		round_time=0
	move_and_slide()
	velocity=Vector2.ZERO

func die():
	dying=true
	$AudioStreamPlayer.play()
	get_parent().shake_camera(5)
	var tween=create_tween().set_ease(Tween.EASE_IN)
	tween.tween_property(self,"scale",Vector2(0.0,0.0),0.5)
	await tween.finished
	queue_free()

func _on_bullet_count_timer_timeout() -> void:
	bullet_count=5
